package controller;

import bean.HomeData;
import service.CommodityService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/shoppingCar")
public class ShoppingCarController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String commodityIdStr=req.getParameter("commodityId");
        String action=req.getParameter("action");
        if(req.getSession().getAttribute("shoppingCar")==null){
            req.getSession().setAttribute("shoppingCar",new ArrayList<>());
        }
        if(commodityIdStr==null||commodityIdStr.isEmpty()||action==null||action.isEmpty()){
            HomeData homeData=new HomeData(null,0,1);
            CommodityService.prepareForShoppingCar(homeData,(List<Integer>) req.getSession().getAttribute("shoppingCar"));
            req.setAttribute("homeData",homeData);
            req.getRequestDispatcher("/shoppingcar.jsp").forward(req, resp);
            return;
        }
        int commodityId=Integer.parseInt(commodityIdStr);
        if(action.equals("add")){
            List<Integer> shoppingCar=(List<Integer>) req.getSession().getAttribute("shoppingCar");
            shoppingCar.add(commodityId);
        }else if(action.equals("remove")){
            List<Integer> shoppingCar=(List<Integer>) req.getSession().getAttribute("shoppingCar");
            int needDeleteIndex=-1;
            for(int i=0;i<shoppingCar.size();i++){
                if (shoppingCar.get(i)==commodityId){
                    needDeleteIndex=i;
                }
            }
            if(needDeleteIndex!=-1){
                shoppingCar.remove(needDeleteIndex);
            }
        }else{
            resp.sendRedirect("shoppingCar.jsp");
        }
        String from=req.getHeader("Referer");
        if(from==null||from.isEmpty()){
            resp.sendRedirect("shoppingCar.jsp");
        }
        resp.sendRedirect(from);
    }
}
